#include "com_form_undrug.h"
#include "ui_com_form_undrug.h"

#include "pub_var.h"
#include <QSettings>
#include <QMessageBox>
#include <QJsonDocument>
#include <QSqlError>

Form_undrug::Form_undrug(QWidget *parent) :
    QWidget(parent),
    ui(new Ui::Form_undrug)
{
    ui->setupUi(this);

    //恢复当前窗口位置
    QSettings setIni("clin.ini", QSettings::IniFormat);
    QRect rct = setIni.value("windowState/undrug").toRect();
    this->setGeometry(rct);

    //数据库连接
    qrm = new QSqlQuery(pub::db_m);
    qro = new QSqlQuery(pub::db_o);
    qrot = new QSqlQuery(pub::db_o);
    md = new QSqlQueryModel();
    md_pop = new QSqlQueryModel();
    md_group = new QSqlQueryModel();

    sq = "select name,code from com_dictionary where  type ='MINFEE' "
         " and valid_state = '1' and code not in('001', '002', '003')";
    qDebug()<<"提取费用类别："<<sq;
    fee_code = pub::fillCombo(ui->cbb_fee_code, sq , -1, qrot);//

    sq = "SELECT name,HIS_CLASS_CODE FROM ORDT_TERM_CLASS where ISDRUG <> '1'";
    qDebug()<<"提取系统类别："<<sq;
    sys_class = pub::fillCombo(ui->cbb_class_code, sq , -1, qrot);//

    sq = "select dept_name, dept_code from com_department "
         "where valid_state = '1' order by dept_name";
    qDebug()<<"提取门诊科室："<<sq;
    oper_dept = pub::fillCombo(ui->cbb_dept_code, sq, -1, qrot);
    pub::fillCombo(ui->cbb_dept_code_2, sq, -1, qrot);
    ui->cbb_dept_code_2->addItem("全部");
    oper_dept.append("^全部^");

    dlg_getItem = new Pub_pop_get_item(this);
}

Form_undrug::~Form_undrug()
{
    delete ui;
}


void Form_undrug::closeEvent(QCloseEvent *event)
{
    Q_UNUSED(event);
    QSettings setIni("clin.ini", QSettings::IniFormat);
    setIni.setValue("windowState/undrug", QVariant(this->geometry()));

    emit destroyW( "undrug" );

}

void Form_undrug::on_pb_search_clicked()
{

    sq = "select item_code 项目编码, item_name 项目名称";
    sq += " from fin_com_undruginfo ";
    sq += " where 1 = 1 ";

    if(ui->ckb_in_use->isChecked())
    {
        sq += " and valid_state = '1' ";
    }
    else
    {
        sq += " and valid_state = '0' ";
    }

    if(ui->ckb_group_item->isChecked())
    {
        sq += " and unitflag = '1' ";
    }
    else
    {
        sq += " and unitflag = '0' ";
    }

    QString key = ui->le_key->text().trimmed();
    sq += " and (item_name like '%" + key + "%' or spell_code like '%" + key.toUpper() + "%')";

    if(!ui->cbb_dept_code_2->currentText().isEmpty()
            && ui->cbb_dept_code_2->currentText() != "全部")
    {
        int pos = pub::searchStr(oper_dept, "^", ui->cbb_dept_code_2->currentText());
        sq += " and exedept_code like '%" + pub::getStr(oper_dept, "^", pos + 1) + "%'";//
    }

    sq += " order by item_name ";

    qDebug()<<"提取非药品项目列表："<<sq;
    md->setQuery(sq, pub::db_o);
    ui->tv_undrug_items->setModel(md);
    pub::setColumnWidth(ui->tv_undrug_items, "0.3^0.55^0^0^0^0^0^0^0^0^0", ui->tv_undrug_items->width());
}

void Form_undrug::on_pb_exit_clicked()
{
    close();
}

void Form_undrug::on_pb_add_clicked()
{
    clear_screen();

    sq = "SELECT SEQ_COM_UNDRUGCODE.NextVal FROM dual";

    qDebug()<<"生成非药品编码："<<sq;
    qro->exec(sq);
    qro->next();
    QString base_code = "F00000000000";
    QString new_code = qro->value(0).toString();
    QString new_drug_code = base_code.replace(base_code.length() - new_code.length(), new_code.length(), new_code);

    ui->le_undrug_code->setText(new_drug_code);
    is_new_item = true;
    //ui->le_undrug_name->setReadOnly(false);//新记录，名称可以编辑
    ui->le_price->setReadOnly(false);//新记录，价格可以编辑
}

void Form_undrug::clear_screen()
{
    ui->le_undrug_code->clear();
    ui->le_undrug_name->clear();
    ui->le_spell_code->clear();
    ui->le_stock_unit->clear();
    ui->le_price->clear();
    ui->le_memo->clear();

    ui->ckb_valid_state->setChecked(false);
    ui->ckb_is_group->setChecked(false);
    ui->ckb_confirm->setChecked(false);

}

bool Form_undrug::check_status()
{
    if(ui->le_undrug_code->text().isEmpty())
    {
        QMessageBox::information(this, "注意", "项目编码不可以为空白！");
        return false;
    }

    if(ui->le_undrug_name->text().trimmed().isEmpty())
    {
        QMessageBox::information(this, "注意", "项目名称不可以为空白！");
        ui->le_undrug_name->setFocus();
        return false;
    }

    if(ui->le_stock_unit->text().trimmed().isEmpty())
    {
        QMessageBox::information(this, "注意", "项目单位不可以为空白！");
        ui->le_stock_unit->setFocus();
        return false;
    }

    if(ui->le_price->text().trimmed().isEmpty())
    {
        QMessageBox::information(this, "注意", "项目价格不可以为空白！");
        ui->le_price->setFocus();
        return false;
    }

    double testDouble = ui->le_price->text().trimmed().toDouble();

    if( qFuzzyCompare(testDouble, 0))
    {
        QMessageBox::warning(this, "注意", "价格为0，请注意核实！");
        //return false;
    }

    if( testDouble + 0.0001 < 0)
    {
        QMessageBox::warning(this, "注意", "价格不可以为负！");
        return false;
    }

    if(ui->cbb_class_code->currentText().isEmpty()
            || ui->cbb_fee_code->currentText().isEmpty()
            )
    {
        //|| ui->cbb_dept_code->currentText().isEmpty()  、执行科室
        QMessageBox::information(this, "注意", "系统类别、费用类别不可以为空白！");
        return false;
    }

    return true;
}

void Form_undrug::on_le_undrug_name_textChanged(const QString &arg1)
{
    if(is_new_item)
    {
        ui->le_spell_code->setText(pub::pub::getFirstLetters(arg1));
    }
}

void Form_undrug::on_tv_undrug_items_clicked(const QModelIndex &index)
{
    is_new_item = false;

    //ui->le_undrug_name->setReadOnly(true);//非新记录，名称不允许编辑
    ui->le_price->setReadOnly(true);//非新记录，价格不可以编辑

    sq = "select item_code, item_name , sys_class, fee_code, "
         "spell_code, unit_price, stock_unit, exedept_code,"
         " valid_state, confirm_flag, mark, unitflag,"
         " collate_flag, special_flag";
    sq += " from fin_com_undruginfo ";
    sq += " where item_code = '" + index.siblingAtColumn(0).data().toString() + "' ";

    //查询项目详细信息
    qDebug()<<"查询项目详细信息 : "<<sq;

    qro->exec(sq);
    qro->next();

    ui->le_undrug_code->setText(qro->value("item_code").toString());
    ui->le_undrug_name->setText(qro->value("item_name").toString());

    int pos;
    QString str = qro->value("sys_class").toString();
    if(str.isEmpty())
    {
        ui->cbb_class_code->setCurrentIndex(-1);
    }
    else
    {
        pos = pub::searchStr(sys_class, "^", str);
        ui->cbb_class_code->setCurrentIndex( ( pos + 1) / 2 - 1 );
    }

    str = qro->value("fee_code").toString();
    if(str.isEmpty())
    {
        ui->cbb_fee_code->setCurrentIndex(-1);
    }else{
        pos = pub::searchStr(fee_code, "^", str);
        ui->cbb_fee_code->setCurrentIndex( ( pos + 1) / 2 - 1 );
    }
    ui->le_spell_code->setText(qro->value("spell_code").toString());
    ui->le_price->setText(qro->value("unit_price").toString());
    ui->le_stock_unit->setText(qro->value("stock_unit").toString());

    str = qro->value("exedept_code").toString();
    if(str.isEmpty())
    {
        ui->cbb_dept_code->setCurrentIndex(-1);
    }
    else
    {
        pos = pub::searchStr(oper_dept, "^", str);
        ui->cbb_dept_code->setCurrentIndex( ( pos + 1) / 2 - 1 );
    }

    if(qro->value("valid_state").toString() == "0")
    {
        ui->ckb_valid_state->setChecked(true);
    }else{
        ui->ckb_valid_state->setChecked(false);
    }

    if(qro->value("confirm_flag").toString() == "1")
    {
        ui->ckb_confirm->setChecked(true);
    }else{
        ui->ckb_confirm->setChecked(false);
    }

    if(qro->value("collate_flag").toString() == "0")
    {
        ui->ckb_is_goods->setChecked(false);
    }else{
        ui->ckb_is_goods->setChecked(true);
    }

    if(qro->value("special_flag").toString() == "0")
    {
        ui->ckb_is_amount->setChecked(false);
    }else{
        ui->ckb_is_amount->setChecked(true);
    }

    if(qro->value("unitflag").toString() == "1")
    {
        ui->ckb_is_group->setChecked(true);

        sq = " select item_name, item_code, his_code,"
             " case when "
             "    (select special_flag "
             "    from fin_com_undruginfo u "
             "    where u.item_code = ZT.his_code and rownum = 1 "
             "    ) = '1' then '是' else '否' end 计费标志 "
             " from fin_com_undrugztinfo zt "
             " where package_code = '" + ui->le_undrug_code->text() + "'";

        qDebug()<<"提取组合项目内容："<<sq;
        md_group->setQuery(sq, pub::db_o);
        ui->tv_group->setModel(md_group);
        pub::setColumnWidth(ui->tv_group, "0.3^0.2^0.2^0.2", ui->tv_group->width());

    }else{
        md_group->setQuery(NULL);
        ui->ckb_is_group->setChecked(false);
    }

    ui->le_memo->setText(qro->value("mark").toString());
}

void Form_undrug::on_pb_save_clicked()
{
    if(!check_status())
    {
        return;
    }

    if(is_new_item)
    {
        sq = "insert into fin_com_undruginfo"
             " (item_code, item_name, sys_class, fee_code, "
             "spell_code, unit_price, stock_unit, exedept_code,"
             " valid_state, confirm_flag, unitflag,"
             "collate_flag, special_flag, "
             "mark, oper_code, oper_date )";
        sq += " values (";
        sq += "'" + ui->le_undrug_code->text() + "',";  //项目编码
        sq += "'" + ui->le_undrug_name->text().trimmed() + "',";  //项目名称

        int pos = pub::searchStr(sys_class, "^", ui->cbb_class_code->currentText());
        sq += "'" + pub::getStr(sys_class, "^", pos + 1) + "',";// class_code '系统类别';

        pos = pub::searchStr(fee_code, "^", ui->cbb_fee_code->currentText());
        sq += " '" + pub::getStr(fee_code, "^", pos + 1) + "',";//  fee_code '最小费用代码';

        sq += "'" + ui->le_spell_code->text().trimmed().toUpper() + "',";
        sq += ui->le_price->text() + ",";
        sq += "'" + ui->le_stock_unit->text().trimmed() + "',";

        if( ui->cbb_dept_code->currentText().isEmpty())
        {
            sq += " '',";//
        }
        else
        {
            pos = pub::searchStr(oper_dept, "^", ui->cbb_dept_code->currentText());
            sq += " '" + pub::getStr(oper_dept, "^", pos + 1) + "',";//
        }

        QString status;
        if(ui->ckb_valid_state->isChecked())
        {
            status = "0";
        }else{
            status = "1";
        }
        sq += "'" + status + "',";   //有效标志

        if(ui->ckb_confirm->isChecked())
        {
            status = "1";
        }else{
            status = "0";
        }
        sq += "'" + status + "',";   //需要诊室确认标志

        if(ui->ckb_is_group->isChecked())
        {
            status = "1";
        }else{
            status = "0";
        }
        sq += "'" + status + "',";   //组套项目标志

        if(ui->ckb_is_goods->isChecked())
        {
            status = "1";
        }else{
            status = "0";
        }
        sq += "'" + status + "',";   //与物资管理关联

        if(ui->ckb_is_amount->isChecked())
        {
            status = "1";
        }else{
            status = "0";
        }
        sq += "'" + status + "',";   //计算项目不收费

        sq += "'" + ui->le_memo->text() + "',";
        sq += "'" + pub::usr_code + "',";
        sq += "sysdate";
        sq += ")";
    }
    else
    {
        sq = "update fin_com_undruginfo set ";
        sq += " item_name = '" + ui->le_undrug_name->text().trimmed() + "',";
        int pos = pub::searchStr(sys_class, "^", ui->cbb_class_code->currentText());
        sq += " sys_class = '" + pub::getStr(sys_class, "^", pos + 1) + "',";// class_code '系统类别';

        pos = pub::searchStr(fee_code, "^", ui->cbb_fee_code->currentText());
        sq += " fee_code = '" + pub::getStr(fee_code, "^", pos + 1) + "',";//  fee_code '最小费用代码';

        sq += " spell_code = '" + ui->le_spell_code->text().trimmed().toUpper() + "',";
        sq += " unit_price = " + ui->le_price->text() + ",";
        sq += " stock_unit = '" + ui->le_stock_unit->text().trimmed() + "',";

        if( ui->cbb_dept_code->currentText().isEmpty())
        {
            sq += " exedept_code = '',";//
        }
        else
        {
            pos = pub::searchStr(oper_dept, "^", ui->cbb_dept_code->currentText());
            sq += " exedept_code = '" + pub::getStr(oper_dept, "^", pos + 1) + "',";//
        }

        QString status;
        if(ui->ckb_valid_state->isChecked())
        {
            status = "0";
        }else{
            status = "1";
        }
        sq += " valid_state = '" + status + "',";   //有效标志

        if(ui->ckb_confirm->isChecked())
        {
            status = "1";
        }else{
            status = "0";
        }
        sq += " confirm_flag = '" + status + "',";   //需要诊室确认标志

        if(ui->ckb_is_goods->isChecked())
        {
            status = "1";
        }else{
            status = "0";
        }
        sq += " collate_flag = '" + status + "',";   //物资关联

        if(ui->ckb_is_amount->isChecked())
        {
            status = "1";
        }else{
            status = "0";
        }
        sq += " special_flag = '" + status + "',";   //是否计费

        if(ui->ckb_is_group->isChecked())
        {
            status = "1";
        }else{
            status = "0";
        }
        sq += " unitflag = '" + status + "',";   //组套项目标志

        sq += " mark = '" + ui->le_memo->text() + "',";
        sq += " oper_code = '" + pub::usr_code + "',";
        sq += " oper_date = sysdate";

        sq += " where item_code = '" + ui->le_undrug_code->text() + "'";  //项目编码 + "'";

    }

    qDebug()<<"变更非药品品种："<<sq;
    if(!qro->exec(sq))
    {
        QMessageBox::information(this, "注意", "操作失败！\n" + qro->lastError().text());
    }
    else
    {
        QMessageBox::information(this, "注意", "记录操作完成！");
        clear_screen();
    }

}

void Form_undrug::on_le_key_returnPressed()
{
    on_pb_search_clicked();
}

